package cn.lkp.mall.ware.service.impl;

import cn.lkp.common.constant.WareConstant;
import cn.lkp.mall.ware.entity.PurchaseDetailEntity;
import cn.lkp.mall.ware.service.PurchaseDetailService;
import cn.lkp.mall.ware.service.WareSkuService;
import cn.lkp.mall.ware.vo.MergeVo;
import cn.lkp.mall.ware.vo.PurchaseDoneVo;
import cn.lkp.mall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.lkp.common.utils.PageUtils;
import cn.lkp.common.utils.Query;

import cn.lkp.mall.ware.dao.PurchaseDao;
import cn.lkp.mall.ware.entity.PurchaseEntity;
import cn.lkp.mall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                //当采购单状态为0或者1时，可以合并整单
                new QueryWrapper<PurchaseEntity>().eq("status",0).or().eq("status",1)
        );
        return new PageUtils(page);
    }
    @Autowired
    PurchaseDetailService purchaseDetailService;

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if(purchaseId==null){
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        //TODO 确认采购单是0新建或1已分配才可以合并采购需求
        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> purchaseDetailEntityList = items.stream().map((i) -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(i);
            detailEntity.setPurchaseId(finalPurchaseId);
            detailEntity.setStatus(WareConstant.PurchaseDetaiStatusEnum.ASSIGNED.getCode());
            return detailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(purchaseDetailEntityList);
        PurchaseEntity entity = new PurchaseEntity();
        entity.setId(purchaseId);
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        this.updateById(entity);

    }

    /**
     * 采购单的id
     * @param ids
     */
    @Override
    public void receive(List<Long> ids) {
        //1.确认当前采购单是新建或已分配状态，才能领取
        List<PurchaseEntity> collect = ids.stream().map(id -> {
            return this.getById(id);
        }).filter(item -> {
            if(item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
               item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()){
                return true;
            }
            return false;
        }).map(item->{
            item.setStatus(WareConstant.PurchaseStatusEnum.RECIEVED.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());
        //2.改变当前采购单的状态
        this.updateBatchById(collect);

        //3.改变当前采购单的采购项的状态
        collect.forEach(item->{
            List<PurchaseDetailEntity> entities = purchaseDetailService.listDetailByPurchaseId(item.getId());
            List<PurchaseDetailEntity> collect1 = entities.stream().map(entity -> {
                PurchaseDetailEntity entity1 = new PurchaseDetailEntity();
                entity1.setId(entity.getId());
                entity1.setStatus(WareConstant.PurchaseDetaiStatusEnum.BUYING.getCode());
                return entity1;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect1);
        });

    }
    @Autowired
    WareSkuService wareSkuService;
    @Transactional
    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {

        //1.改变采购项状态
        Boolean flag = true;
        List<PurchaseItemDoneVo> items = purchaseDoneVo.getItems();
        //List<PurchaseDetailEntity> updates = new ArrayList<>();
        for(PurchaseItemDoneVo item:items){
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            if(item.getStatus() == WareConstant.PurchaseDetaiStatusEnum.HASERROR.getCode()){
                flag = false;
                detailEntity.setStatus(item.getStatus());
            }else{
                detailEntity.setStatus(WareConstant.PurchaseDetaiStatusEnum.FINISH.getCode());
            }
            //detailEntity.setId(item.getItemId());
            purchaseDetailService.update(detailEntity,new QueryWrapper<PurchaseDetailEntity>().eq("purchase_id",purchaseDoneVo.getId()).eq("sku_id",item.getItemId()));
            //updates.add(detailEntity);
        }
        //updateBatchById方法返回有误，改用在for循环里面使用update方法，拼接条件。
        //purchaseDetailService.updateBatchById(updates);
        //2.改变采购单状态
        Long id = purchaseDoneVo.getId();
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
        //3.将采购成功的进行入库
        //PurchaseDetailEntity entity = purchaseDetailService.getById(item.getItemId());
        try{
            //采购项状态更新成功后，重新查询当前采购单中采购项状态为已完成的记录
            List<PurchaseDetailEntity> entities = purchaseDetailService.list(new QueryWrapper<PurchaseDetailEntity>().eq("purchase_id",id).eq("status", WareConstant.PurchaseDetaiStatusEnum.FINISH.getCode()));
            if(entities!=null && entities.size()>0){
                for(PurchaseDetailEntity entity:entities){
                    wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());
                }
            }
        }catch(Exception e){
        }
    }
}